package com.AuthServer.utils;

import com.AuthServer.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

@Slf4j
public class GraphicalCaptchaUtil {

    // 随机产生数字与字母组合的字符串
    private static final String randString = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final int width = 95;// 图片宽
    private static final int height = 25;// 图片高
    private static final int lineSize = 40;// 干扰线数量
    private static final int stringNum = 4;// 随机产生字符数量
    private static final Random random = new Random();// 随机数对象

    /**
     * 获得字体
     */
    private static Font getFont() {
        return new Font("Fixedsys", Font.BOLD, 18);
    }

    /**
     * 获得颜色
     */
    private static Color getRandColor(int fc, int bc) {
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int boundR = Math.max(bc - fc - 16, 1); // Ensure the bound is at least 1
        int boundG = Math.max(bc - fc - 14, 1);
        int boundB = Math.max(bc - fc - 18, 1);
        int r = fc + random.nextInt(boundR);
        int g = fc + random.nextInt(boundG);
        int b = fc + random.nextInt(boundB);
        return new Color(r, g, b);
    }

    /**
     * 生成随机图片
     */
    public static Result<String> getRandomCode(String userId, RedisTemplate<String,Object> template) throws IOException{
        log.info("userId is "+userId+" doing getRandomCode");
        // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        // 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
        Graphics g = image.getGraphics();
        g.fillRect(0, 0, width, height);//图片大小
        g.setFont(new Font("Times New Roman", Font.PLAIN, 18));//字体大小
        g.setColor(getRandColor(random.nextInt(301), random.nextInt(301)));//字体颜色
        // 绘制干扰线
//        for (int i = 0; i <= lineSize; i++) {
//            drawLine(g);
//        }
        IntStream.rangeClosed(0, lineSize).forEach(i -> drawLine(g));

        // 绘制随机字符
        String randomString = "";
//        for (int i = 1; i <= stringNum; i++) {
//            randomString = drawString(g, randomString, i);
//        }
        StringBuilder randomStringBuilder = new StringBuilder();
        String finalRandomString = randomString;
        IntStream.rangeClosed(1, stringNum)
                .forEach(i -> randomStringBuilder.append(drawString(g, finalRandomString,i)));
        randomString = randomStringBuilder.toString();
        g.dispose();
        log.info("randomString is "+randomString);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "JPEG", outputStream);

        byte[] imageBytes = outputStream.toByteArray();
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);

        template.opsForValue().set(userId+"_code",randomString,2, TimeUnit.MINUTES);

        return Result.success(base64Image);
    }

    /**
     * 绘制字符串
     */
    private static String drawString(Graphics g, String randomString, int i) {
        g.setFont(getFont());
        g.setColor(new Color(random.nextInt(101), random.nextInt(111), random
                .nextInt(121)));
        String rand = getRandomString(random.nextInt(randString
                .length()));
        randomString += rand;
        g.translate(random.nextInt(3), random.nextInt(3));
        g.drawString(rand, 13 * i, 16);
        return randomString;
    }

    /**
     * 绘制干扰线
     */
    private static void drawLine(Graphics g) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(13);
        int yl = random.nextInt(15);
        g.drawLine(x, y, x + xl, y + yl);

    }

    /**
     * 获取随机的字符
     */
    public static String getRandomString(int num) {
        return String.valueOf(randString.charAt(num));
    }

}
